package ejb.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import ejb.entity.City;
import ejb.entity.Forecast;

@Stateless
public class DefaultForecastDAO implements ForecastDAO {
	
	@PersistenceContext
	private EntityManager em;
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Forecast> findAll() {
		return em.createNamedQuery("DefaultForecast.findAll").getResultList();
	}
	
	@Override
	public Forecast findByCityAndDay(City city, int plusday) {
		try {
		return (Forecast) em
			.createNamedQuery("DefaultForecast.findForCityAndDay")
			.setParameter("city", city)
			.setParameter("plusday", plusday)
			.getSingleResult();
		}catch(NoResultException nre){
			return null;
		}catch(IllegalArgumentException e){
			return null;
		}
	}
	
	@Override 
	public Forecast create(Forecast forecast) {
		try{
			em.persist(forecast);
		}catch(IllegalArgumentException e){
			return null;
		}
		return forecast;
	}

}
